package logic

import (
	"context"
	"time"

	"mall/common/cryptx"
	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ResetPasswordLogic) ResetPassword(in *backend.ResetPasswordRequest) (*backend.ResetPasswordResponse, error) {
	if in.Id == 0 {
		return nil, errorx.Status(errorx.ERROR_USER_ID_REQUIRED, "")
	}

	password, err := cryptx.GenerateRandomHexString(6)
	if err != nil {
		return nil, errorx.Status(errorx.ERROR_GENERATE_PASSWORD_EXCEPTION, "")
	}

	salt, err := cryptx.GenerateRandomHexString(16)
	if err != nil {
		return nil, errorx.Status(errorx.ERROR_GENERATE_PASSWORD_EXCEPTION, "")
	}

	var user model.BackendUser
	user.ID = uint64(in.Id)
	user.Password = cryptx.PasswordEncrypt(salt, password)
	user.Salt = salt
	user.LastUpdatedBy = uint64(in.UpdatedBy)
	user.UpdatedAt = time.Now()

	_, err = l.svcCtx.BackendUser.ResetPassword(l.ctx, &user)
	if err != nil {
		return nil, err
	}

	return &backend.ResetPasswordResponse{
		Password: password,
	}, nil
}
